﻿const postmessage = (command, reqdata) =>
	new Promise((ok) => {
		chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
			const tabId = tabs.length ? tabs[0].id : null;
			const connect = chrome.tabs.connect(tabId, { name: "bosstools" });
			connect.postMessage({ command, reqdata });
			connect.onMessage.addListener((mess) => {
				ok(mess);
			});
		});
	});

const localscope = (main) => {
	main();
};

window.onload = async () => {
	const waiting_dom = document.getElementById("WAITING_TIME");
	const open_dom = document.getElementById("OPEN_THE_TOOLS");
	const send_message = document.getElementById("SEND_MESSAGE");
	// 启动
	open_dom.addEventListener("change", ({ target: { checked } }) => {
		postmessage("setdata", { open_the_tools: checked });
	});

	// 等待时间
	waiting_dom.addEventListener("change", function ({ target: { value } }) {
		if (value <= 1000) value = 1000;
		waiting_dom.value = value;
		postmessage("setdata", { waiting_time: value });
		this.blur();
	});

	// 打招呼信息
	send_message.addEventListener("change", function ({ target: { value } }) {
		const send_messages = value.split("\n").filter((e) => e);
		postmessage("setdata", { send_messages });
		this.blur();
	});

	localscope(async () => {
		try {
			const { waiting_time, open_the_tools, send_messages } = await postmessage("getdata");
			waiting_dom.value = waiting_time;
			open_dom.checked = open_the_tools;
			send_message.value = send_messages.join("\n");
		} catch (error) {
			console.warn("当前页面不支持使用！");
		}
	});
};
